package org.pearl.thread.demo.test001;

import java.util.concurrent.TimeUnit;

/**
 * Created by TD on 2021/4/13
 */
public class InterruptThreadTest001 {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println(Thread.currentThread().getName() + "正在检测心跳");
                    System.out.println("中断状态" + Thread.interrupted());
                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        // 被中断时 退出循环
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }, "检测心跳任务线程");
        // 获取当前线程
        t.start();
        try {
            Thread.sleep(20_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 中断
        t.interrupt();
        System.out.println(Thread.currentThread().getName() + "线程任务运行结束");
    }
}
